#encoding=utf8
'''
Created on Dec 18, 2014

@author: jingyang <jingyang@smalltreemedia.com>
'''
from celery.task import task
import gspread

import settings
from ads_info.models import AdsInfo


# python manage.py celery worker -B --scheduler=djcelery.schedulers.DatabaseScheduler

@task()
def print_test():
    print 'Hello World.'


ID_INDEX = {
    # unit name: col num in the sheet,
    'MoPub - Phone Banner': 16,
    'MoPub - Phone FullScreen': 17,
    'MoPub - Phone Rectangle': 18,
    'MoPub - Pad Banner': 19,
    'MoPub - Pad FullScreen': 20,
    'MoPub - Pad Rectangle': 21,
    'InMobi - ID': 22,
    'MoPub Cross Promo - Phone FullScreen': 26,
    'MoPub Cross Promo - Tablet FullScreen': 27,
}


def _login():
    gc = gspread.login(settings.WRITER_EMAIL, settings.WRITER_PWD)
    wks = gc.open(settings.ADS_ID_FILE).sheet1
    return wks


@task()
def get_ads_id():
    """
    get ads id in google sheet: 2015 Ads Request Tracker - Universal
    """
    wks = _login()
    req_ids = wks.col_values(1)[2:]
    print 'Starting...'
    for k, v in enumerate(req_ids):
        try:
            info = AdsInfo.objects.get(request_id=v)
        except Exception, e:
            print 'Row: %s %s' % (k + 3, e)
            continue
        if not info.status == 'N':
            continue
        try:
            status = wks.cell(k + 3, 12).value
            if status == 'Ad Setup Completed':
                units = info.get_units()
                for u in units:
                    u.value = wks.cell(k + 3, ID_INDEX.get(u.unit.__unicode__())).value
                    u.save()
                info.status = 'F'
            elif status == 'Request Cancelled':
                info.status = 'C'
            elif status == 'Invalid Request':
                info.status = 'I'
            info.save()
            print 'Request ID: %s Done.' % v
        except Exception, e:
            print e
            wks = _login()
            continue
    print 'All Done.'
